package servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import custom.User;

/**
 * Servlet implementation class NewAccServlet
 */
@WebServlet("/NewAccServlet")
public class NewAccServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public NewAccServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String userName = request.getParameter("userName");
		String password = request.getParameter("password1");
		String password2 = request.getParameter("password2");
		
		RequestDispatcher dispatch;
		if(userName.length()*password.length()*password2.length() ==0){
			request.getSession().setAttribute("Note", "Please, fill all the fields");
			dispatch = request.getRequestDispatcher("newAccount.jsp");
		}else if(!password.equals(password2)){
			request.getSession().setAttribute("Note", "You entered different Passwords. <p></p> Please try again");
			dispatch = request.getRequestDispatcher("newAccount.jsp");
		}else{
			request.getSession().setAttribute("user",User.register(userName, password));
			if(request.getSession().getAttribute("user") == null){
				request.getSession().setAttribute("Note", "The username you entered is not available. <p></p> Please try again");
				dispatch = request.getRequestDispatcher("newAccount.jsp");
			}else
				dispatch = request.getRequestDispatcher("Home.jsp");
		}
		dispatch.forward(request, response);
	}

}
